<template>
  <!-- <doc-alert title="【商品】商品分类11122" url="https://doc.iocoder.cn/mall/product-category/" /> -->

  <!-- 搜索工作栏 -->
  <ContentWrap :show-border="false">
    <el-form
      class="-mb-15px search-form"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="分类名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入分类名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <!-- <el-form-item class="p-0 m-0" style="border: none !important">
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>

      </el-form-item> -->
      <el-form-item class="p-0 m-0" style="border: none !important">
        <el-button @click="handleQuery" type="primary" color="#3721FF"> 搜索</el-button>
        <el-button style="border: none !important" @click="resetQuery">
          <Icon class="mr-5px" icon="ant-design:clear-outlined" />
          清除条件
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap :show-border="false">
    <el-row :gutter="10" class="mb6">
      <el-col :span="1.5" class="el-btn">
        <el-button
          type="primary"
          color="#3721FF"
          @click="openForm('create')"
          v-hasPermi="['product:category:create']"
        >
          <Icon icon="ep:plus" class="mr-2px" />
          新增分类
        </el-button>
      </el-col>
      <el-col :span="1.5" class="el-btn">
        <el-button type="default" v-hasPermi="['product:category:create']"> 保存</el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      row-key="id"
      default-expand-all
      :header-cell-style="{ backgroundColor: '#F7F7FB', color: '#333' }"
      class="rounded-lg"
    >
      <el-table-column label="分类名称" min-width="240" prop="name">
        <template #default="{ row }">
          <span> | {{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品数量" min-width="240" prop="productCount" />
      <!--      <el-table-column label="分类图标" align="center" min-width="80" prop="picUrl">-->
      <!--        <template #default="scope">-->
      <!--          <img :src="scope.row.picUrl" alt="移动端分类图" class="h-36px" />-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="排序" align="center" min-width="150" prop="sort" />-->
      <!--      <el-table-column label="状态" align="center" min-width="150" prop="status">-->
      <!--        <template #default="scope">-->
      <!--          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="创建者" prop="nickName" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
      />
      <el-table-column label="操作" align="center" min-width="180">
        <template #default="scope">
          <el-button
            link
            plain
            color="#3721FF"
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['product:category:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            plain
            color="#3721FF"
            type="primary"
            @click="handleViewProduct(scope.row.id)"
            v-hasPermi="['product:category:update']"
          >
            关联商品
          </el-button>
          <!-- 子列表操作栏不显示这个按钮 -->
          <!-- 第一层才需要展示添加子级按钮 -->
          <el-button
            v-if="scope.row.parentId === 0"
            link
            plain
            color="#3721FF"
            type="primary"
            @click="handleAddSubsetPops(scope.row)"
            v-hasPermi="['product:category:update']"
          >
            添加子级
          </el-button>
          <el-button
            link
            type="primary"
            v-if="scope.row.parentId > 0"
            @click="handleViewSpu(scope.row.id)"
            v-hasPermi="['product:spu:query']"
          >
            查看商品
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['product:category:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CategoryForm ref="formRef" @success="getList" />
  <RelatedGoods
    ref="relatedGoodsRef"
    :showDot="true"
    @confirm="handleRelatedGoodsConfirm"
    width="40%"
    title="关联商品"
  />
  <!-- 添加子集 -->
  <!-- <ComfirmPops
    ref="addSubsetPopsRef"
    :show-icon="false"
    width="500px"
    :show-dot="true"
    type="Tips"
    title="编辑分类"
    @confirm="getAddSubsetPops"
  >
    <template #content>
      <div>
        <el-form ref="formRef" :model="classForm" label-width="80px">
          <el-form-item label="上级分类" prop="name">
            <el-input v-model="classForm.name" placeholder="请输入分类名称" />
          </el-form-item>
          <el-form-item label="分类名称" prop="name">
            <el-input v-model="classForm.name" placeholder="请输入分类名称" />
          </el-form-item>
        </el-form>
      </div>
    </template>
  </ComfirmPops> -->
  <!-- 正常删除弹窗 -->
  <ComfirmPops
    ref="deletePopsRef"
    :show-icon="true"
    width="500px"
    :show-dot="false"
    type="idTips"
    title="删除"
    :id="delSelected"
    @confirm="getDeletePops"
  >
    <template #content>
      <p>确定删除吗？</p>
    </template>
  </ComfirmPops>
</template>
<script lang="ts" setup>
import { DICT_TYPE } from '@/utils/dict'
import { handleTree } from '@/utils/tree'
import { dateFormatter } from '@/utils/formatTime'
import RelatedGoods from './relatedGoods.vue'
import * as ProductCategoryApi from '@/api/mall/product/category'
import CategoryForm from './CategoryForm.vue'
import { throttle } from '@/utils'

defineOptions({ name: 'ProductCategory' })
const addSubsetPopsRef = ref()
const deletePopsRef = ref() // 删除弹窗的Ref
const delSelected = ref(0) // 删除的ID

const classForm = reactive({
  name: ''
})
const classRules = reactive({
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
})
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const relatedGoodsRef = ref() // 关联商品弹窗
const loading = ref(true) // 列表的加载中
const list = ref<any[]>([]) // 列表的数据
const queryParams = reactive({
  name: undefined
})
const queryFormRef = ref() // 搜索的表单

const selectedCategoryId = ref(null)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProductCategoryApi.getCategoryList(queryParams)
    list.value = handleTree(data, 'id', 'parentId')
  } finally {
    loading.value = false
  }
}
const getAddSubsetPops = () => {}
const handleAddSubsetPops = (row) => {
  // addSubsetPopsRef.value?.show()
  formRef.value.open('1', row.id, row.parentId)
}
/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}
const getDeletePops = async (res: boolean, id: number) => {
  console.log('isConfirm', res, id)

  if (res) {
    // await ProductSpuApi.deleteSpu(id)

    await ProductCategoryApi.deleteCategory(delSelected.value)

    await getList()
    message.success('删除成功')
    // deletePopsRef.value.hide()
  } else {
    // deletePopsRef.value.hide()
  }
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  delSelected.value = id
  deletePopsRef.value.show()
  //
  // await getList()
  // try {
  //   // 删除的二次确认
  //   await message.delConfirm()
  //   // 发起删除
  //   await ProductCategoryApi.deleteCategory(id)
  //   message.success(t('common.delSuccess'))
  //   // 刷新列表
  //   await getList()
  // } catch {}
}

/** 查看商品操作 */
const router = useRouter() // 路由
const handleViewSpu = (id: number) => {
  router.push({
    name: 'ProductSpu',
    query: { categoryId: id }
  })
}
const handleViewProduct = (id: number) => {
  selectedCategoryId.value = id
  relatedGoodsRef.value?.show(id)
}

/**
 * 关联商品点击确定
 * */
const handleRelatedGoodsConfirm = throttle(async (productList) => {
  // 根据类别 保存商品
  try {
    await ProductCategoryApi.updateCategoryProductList({
      categoryId: selectedCategoryId.value,
      ids: productList.map((item) => {
        return item.id
      })
    }).then(() => {
      message.success('关联成功')
    })
  } catch (e) {
    console.log(e)
  }

  console.log('点击保存商品分类')
}, 1000)

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
<style scoped>
@import '@/styles/website.scss';
</style>
<style lang="scss" scoped></style>
